package hkppay

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"net/http"
	"net/url"

	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"
)

func SendRequest(ctx context.Context, targetUrl string, data map[string]string) (string, error) {
	bodyStr, _ := sonic.MarshalString(data)

	formData := url.Values{}
	for key, val := range data {
		formData.Add(key, val)
	}
	body := formData.Encode()

	req, err := http.NewRequest(http.MethodPost, targetUrl, bytes.NewBufferString(body))
	if err != nil {
		return "", err
	}

	// Set the appropriate headers
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")

	// Create a new HTTP client and send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Read the response body
	bodyResp, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	resStr := string(bodyResp)

	fmt.Printf("URL: %s\nData: %s\nResponse: %s\n", targetUrl, bodyStr, resStr)
	logc.Info(ctx, fmt.Sprintf("url:%s bodyReq:%s bodyResp:%s", targetUrl, bodyStr, resStr))

	return resStr, nil
}
